package org.angelica.modules.account.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import org.angelica.core.response.ResponseResult;
import org.angelica.core.wrapper.ResponseWrapper;
import org.angelica.modules.account.entity.AccUserDO;
import org.angelica.modules.account.form.AccUserCreateForm;
import org.angelica.modules.account.form.AccUserUpdateForm;
import org.angelica.modules.account.query.AccUserQuery;
import org.angelica.modules.account.service.AccUserService;
import org.angelica.utils.security.BcryptUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Calendar;
import java.util.Map;

/**
 * <p>
 * 管理员表 前端控制器
 * </p>
 *
 * @author aizhimin
 * @since 2019-05-12
 */
@RestController
@RequestMapping("api/account/accUser")
public class AccUserController {

    @Autowired
    private AccUserService accUserService;

    @GetMapping("/")
    public ResponseResult listAccUser(AccUserQuery accUserQuery){
        IPage<AccUserDO> accUserPage = accUserService.listAccUser(accUserQuery);
        return ResponseResult.success("data", ResponseWrapper.wrapperPage(accUserPage));
    }

    /**
     * 页面初始化数据
     * @return
     */
    private Map<String,Object> initData(){
        AccUserQuery accUserQuery = new AccUserQuery();
        IPage<AccUserDO> adminUserPage = accUserService.listAccUser(accUserQuery);
        return ResponseWrapper.wrapperPage(adminUserPage);
    }

    @GetMapping("/{id}")
    public ResponseResult getAccUser(@PathVariable(value = "id")Long id){
        AccUserDO accUserDO = accUserService.getById(id);
        return ResponseResult.success("data", accUserDO);
    }

    @PostMapping("/create")
    public ResponseResult createAccUser(@RequestBody @Valid AccUserCreateForm accUserCreateForm){
        AccUserDO accUserDO = AccUserDO.builder().build();
        BeanUtils.copyProperties(accUserCreateForm,accUserDO);
        //设置默认密码
        accUserDO.setPassword(BcryptUtil.encodePassword("123456"));
        accUserDO.setGmtCreate(Calendar.getInstance().getTime());
        accUserService.save(accUserDO);
        return ResponseResult.success("data",initData());
    }

    @PostMapping("/update")
    public ResponseResult updateAccUser(@RequestBody @Valid AccUserUpdateForm accUserUpdateForm){
        AccUserDO accUserDO = AccUserDO.builder().build();
        BeanUtils.copyProperties(accUserUpdateForm,accUserDO);
        accUserDO.setGmtModified(Calendar.getInstance().getTime());
        accUserService.updateById(accUserDO);
        return ResponseResult.success("data",initData());
    }

    @GetMapping("/delete/{id}")
    public ResponseResult deleteAccUser(@PathVariable(value = "id")Long id){
        accUserService.removeById(id);
        return ResponseResult.success("data",initData());
    }

}
